<?php
namespace app\admin\controller;

use app\common\model\AdminIpsModel;
use app\common\model\AdminModel;
use app\common\model\MenuModel;
use app\common\model\RoleModel;

/**
 * 管理员控制器
 * @author 贺强
 * @time   2021-06-21 16:52:19
 */
class Admin extends Common
{
    /**
     * 添加管理员账号
     * @author 贺强
     * @time   2018-10-25 14:11:14
     * @param  AdminModel $a AdminModel 实例
     */
    public function add(AdminModel $a)
    {
        if ($this->request->isAjax()) {
            $param = $this->request->post();
            if (empty($param['username']) || empty($param['password']) || empty($param['role_id'])) {
                return ['status' => 1, 'info' => '非法参数'];
            }
            $has = $a->getCount([['is_delete', '=', 0], ['username', '=', $param['username']]]);
            if (!empty($has)) {
                return ['status' => 2, 'info' => '该账号已存在'];
            }
            $param['password'] = get_password($param['password']);
            $param['status']   = 1;
            // 随机头像
            $param['avatar'] = '/static/h+/img/a' . mt_rand(1, 9) . '.jpg';
            // 数据入库
            $res = $a->add($param);
            if (!$res) {
                return ['status' => 4, 'info' => '添加失败'];
            }
            return ['status' => 0, 'info' => '添加成功'];
        } else {
            $where = [['id', '<>', 1]];
            $roles = $this->getRoles($where);
            return $this->fetch('add', ['roles' => $roles]);
        }
    }

    /**
     * 设置管理员
     * @author 贺强
     * @time   2018-10-25 14:14:27
     * @param  AdminModel $a AdminModel 实例
     */
    public function operate(AdminModel $a)
    {
        if (!empty($admin['status'])) {
            return $admin;
        }
        $ids = $this->request->post('ids');
        if (empty($ids) || !preg_match('/^0[\,\d+]+$/', $ids)) {
            return ['status' => 3, 'info' => '非法参数'];
        }
        $type = $this->request->post('type');
        if (empty($type)) {
            return ['status' => 1, 'info' => '非法操作'];
        }
        if ($type === 'del' || $type === 'delAll') {
            $field = 'is_delete';
            $value = 1;
            $msg   = '删除';
        } elseif ($type === 'disable' || $type === 'disableAll') {
            $field = 'status';
            $value = 4;
            $msg   = '禁用';
        } elseif ($type === 'enable' || $type == 'enableAll') {
            $field = 'status';
            $value = 1;
            $msg   = '启用';
        } elseif ($type === 'nipAll') {
            $field = 'is_ip';
            $value = 1;
            $msg   = '限制IP';
        } elseif ($type === 'mipAll') {
            $field = 'is_ip';
            $value = 0;
            $msg   = '免IP';
        } else {
            return ['status' => 2, 'info' => '非法操作'];
        }
        $res = $a->modifyField($field, $value, [['id', 'in', $ids]]);
        if ($res) {
            return ['status' => 0, 'info' => $msg . '成功'];
        } elseif ($res === false) {
            return ['status' => 4, 'info' => $msg . '失败'];
        } else {
            return ['status' => 5, 'info' => '该账号已' . $msg];
        }
    }

    /**
     * 添加 IP 白名单
     * @author 贺强
     * @time   2021-09-14 18:35:25
     * @param  AdminIpsModel $i AdminIpsModel 实例
     */
    public function addip(AdminIpsModel $i)
    {
        // 判断是否有权限访问或操作
        $identity = strtolower($this->request->controller()) . '_' . strtolower($this->request->action());
        $admin    = $this->is_valid($identity);
        if ($this->request->isAjax()) {
            $param = $this->request->post();
            if (empty($param['ip'])) {
                return ['status' => 1, 'info' => 'IP不能为空'];
            }
            $param['ip'] = trim($param['ip']);
            // 插入数据库
            $count = $i->getCount(['ip' => $param['ip']]);
            if ($count) {
                return ['status' => 2, 'info' => '此IP已加入白名单'];
            }
            if (!empty($param['username'])) {
                $i->delByWhere(['username' => $param['username']]);
            }
            $res = $i->add($param);
            if (!$res) {
                return ['status' => 4, 'info' => '添加失败'];
            }
            return ['status' => 0, 'info' => '添加成功'];
        }
        $list = $i->getList([['username', '<>', '']], ['distinct username'], '', 'username');
        return $this->fetch('addip', ['list' => $list]);
    }

    /**
     * 后台 IP 白名单
     * @author 贺强
     * @time   2021-09-14 18:33:29
     * @param  AdminIpsModel $i AdminIpsModel 实例
     */
    public function ips(AdminIpsModel $i)
    {
        // 判断是否有权限访问或操作
        $identity = strtolower($this->request->controller()) . '_' . strtolower($this->request->action());
        $admin    = $this->is_valid($identity);
        $where    = [];
        $keyword  = $this->request->post('keyword', '');
        if (!empty($keyword)) {
            $where[] = ['ip', 'like', "%{$keyword}%"];
        }
        // 分页参数
        $page     = intval($this->request->get('page', 1));
        $pagesize = intval($this->request->get('pagesize', config('PAGESIZE')));
        $list     = $i->getList($where, true, "$page,$pagesize", ['login_time' => 'desc']);
        // print_r($list);exit;
        foreach ($list as &$item) {
            // $item['status_txt'] = '禁用';
            // if ($item['status']) {
            //     $item['status_txt'] = '正常';
            // }
            if (!empty($item['login_time'])) {
                format_datetime($item['login_time']);
            }
            if (!empty($item['ctime'])) {
                format_datetime($item['ctime']);
            }
        }
        $count = $i->getCount($where);
        $pages = ceil($count / $pagesize);
        return $this->fetch('ips', ['list' => $list, 'pages' => $pages, 'keyword' => $keyword]);
    }

    /**
     * 操作 IP 白名单
     * @author 贺强
     * @time   2021-09-14 18:36:25
     * @param  AdminIpsModel $i AdminIpsModel 实例
     */
    public function operate_ip(AdminIpsModel $i)
    {
        // 判断是否有权限访问或操作
        $identity = strtolower($this->request->controller()) . '_' . strtolower($this->request->action());
        $admin    = $this->is_valid($identity);
        if (!empty($admin['status'])) {
            return $admin;
        }
        if ($this->request->isAjax()) {
            $ids = $this->request->post('ids');
            if (empty($ids) || !preg_match('/^0[\,\d+]+$/', $ids)) {
                return ['status' => 3, 'info' => '非法参数'];
            }
            $type = $this->request->post('type');
            if (empty($type)) {
                return ['status' => 1, 'info' => '非法操作'];
            }
            $where = [['id', 'in', $ids]];
            if ($type === 'del' || $type === 'delAll') {
                $res = $i->delByWhere($where);
                $msg = '删除';
            } else {
                return ['status' => 2, 'info' => '非法操作'];
            }
            if ($res) {
                return ['status' => 0, 'info' => $msg . '成功'];
            } elseif ($res === false) {
                return ['status' => 4, 'info' => $msg . '失败'];
            } else {
                return ['status' => 5, 'info' => '该ip已' . $msg];
            }
        } else {
            return ['status' => 2, 'info' => '非法操作'];
        }
    }

    /**
     * 修改管理员
     * @author 贺强
     * @time   2018-10-25 14:13:59
     * @param  AdminModel $a AdminModel 实例
     */
    public function edit(AdminModel $a)
    {
        $admin = $this->admin;
        $uname = $admin['username'];
        $rid   = $admin['role_id'];
        if ($this->request->isAjax()) {
            $param = $this->request->post();
            $id    = $admin['id'];
            $pau   = $param['username'];
            if ($rid === 1) {
                $id = $param['id'];
            } elseif ($uname !== $pau) {
                return ['status' => 1, 'info' => '非法操作，只能修改自己的账号'];
            }
            if ($rid !== 1) {
                unset($param['role_id']);
            }
            $is_pwd = false;
            if (!empty($param['password'])) {
                $pwd = $param['password'];
                $len = strlen($pwd);
                $s1  = preg_match("/^[1-9]*$/", $pwd);
                $s2  = preg_match("/^[a-z]*$/", $pwd);
                $s3  = preg_match("/^[A-Z]*$/", $pwd);
                if ($len < 6 || $s1 || $s2 || $s3) {
                    return ['status' => 2, 'info' => '密码不能少于6位，且不能为全数字，全小写，全大写'];
                }
                $param['password'] = get_password($pwd);
		// 重新登录
                $is_pwd = true;
            } else {
                unset($param['password']);
            }
            unset($param['username']);
            // 执行修改
            $res = $a->modify($param, ['id' => $id]);
            if (!$res) {
                return ['status' => 4, 'info' => '修改失败'];
            }
            $msg    = '修改成功';
            $status = 0;
            if ($is_pwd) {
                $status = 88;
                $msg    = '密码重修成功，请重新登录';
            }
            return ['status' => $status, 'info' => $msg];
        }
        $id = $this->request->get('id');
        if (empty($id) || !is_numeric($id)) {
            $id = $admin['id'];
        }
        $user = $a->getModel(['id' => $id]);
        if (empty($user)) {
            $user = $a->getModel(['id' => $admin['id']]);
        }
        if (empty($user)) {
            $this->error('用户不存在');
        }
        $role_w = null;
        if ($uname !== 'admin') {
            $role_w = [['id', '<>', 1]];
        }
        $roles = $this->getRoles($role_w);
        return $this->fetch('edit', compact('user', 'uname', 'roles'));
    }

    /**
     * 管理员列表
     * @author 贺强
     * @time   2018-10-25 14:14:10
     * @param  AdminModel $a AdminModel 实例
     */
    public function lists(AdminModel $a)
    {
        $where   = [['is_delete', '=', 0], ['username', '<>', 'admin']];
        $keyword = '';
        $type    = 0;
        $param   = $this->request->get();
        //print_r($param);exit;
        if (!empty($param['keyword'])) {
            $where[] = ['username', 'like', "%{$param['keyword']}%"];
        } else {
            $param['keyword'] = '';
        }
        if (!empty($param['type']) && is_numeric($param['type'])) {
            $where[] = ['role_id', '=', $param['type']];
        } else {
            $param['type'] = 0;
        }
        //按状态条件搜索
        if (!empty($param['status']) && is_numeric($param['status'])) {
            $where[] = ['status', '=', $param['status']];
        } else {
            $param['status'] = 0;
        }
        // 分页参数
        $page     = $param['page'] ?? 1;
        $pagesize = $param['pagesize'] ?? config('PAGESIZE');
        $list     = $a->getList($where, true, "$page,$pagesize", ['login_time' => 'desc']);
        // var_dump($list);exit;
        foreach ($list as &$item) {
            $item['status_txt'] = get_user_status($item['status']);
            if ($item['is_ip']) {
                $item['is_ip_txt'] = '是';
            } else {
                $item['is_ip_txt'] = '否';
            }
            if (!empty($item['login_time'])) {
                format_datetime($item['login_time']);
            }
            if (!empty($item['ctime'])) {
                format_datetime($item['ctime']);
            }
        }
        $count  = $a->getCount($where);
        $pages  = ceil($count / $pagesize);
        $roles  = $this->getRoles([['id', '<>', 1]]);
        $status = [['id' => 1, 'name' => '正常'], ['id' => 4, 'name' => '禁用']];
        $m      = new MenuModel();
        $is_ip  = $m->getFieldValue('is_hide', ['identity' => 'admin_ips']) ? 0 : 1;
        return $this->fetch('list', compact('list', 'roles', 'status', 'pages', 'is_ip', 'param'));
    }

    /**
     * 获取用户角色
     * @author 贺强
     * @time   2018-10-30 15:16:13
     */
    private function getRoles($where = ['status' => 1])
    {
        $r    = new RoleModel();
        $list = $r->getList($where, ['id', 'role_name']);
        return $list;
    }
}
